package service

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"student/model"
)

type StudentService struct {
	Cid     int
	Student []model.Student
}

func (ss *StudentService) AddStu() {
	var (
		name  string
		age   int8
		email string
	)

	fmt.Printf("请输入学生的姓名： ")
	fmt.Scan(&name)

	fmt.Printf("请输入学生的年龄： ")
	fmt.Scan(&age)

	fmt.Printf("请输入学生的邮箱： ")
	fmt.Scan(&email)
	ss.Cid++
	var Newstu = model.Student{
		Cid:   ss.Cid,
		Name:  name,
		Age:   age,
		Email: email,
	}

	ss.Student = append(ss.Student, Newstu)
}

func (ss StudentService) ListStu() {
	for _, v := range ss.Student {
		fmt.Printf("编号：%-8d 姓名：%-8s 年龄：%-8d 邮箱：%-8s\n", v.Cid, v.Name, v.Age, v.Email)
	}
}

func (ss *StudentService) stuIsExist(inputNum int) int {
	var changeNum = -1
	for k, v := range ss.Student {
		if v.Cid == inputNum {
			changeNum = k
		}
	}
	return changeNum
}

func (ss *StudentService) ChangeStu() {
	for {
		fmt.Printf("请输入需要修改的学生编号： ")
		var updateNum int
		fmt.Scan(&updateNum)
		changeNum := ss.stuIsExist(updateNum)
		if changeNum != -1 {
			var updateStu = &ss.Student[changeNum]

			var (
				name  string
				age   int8
				email string
			)
			fmt.Printf("请输入需要修改的姓名（原：%s）：", updateStu.Name)
			fmt.Scanln(&name)
			if name != "" {
				updateStu.Name = name
			}

			fmt.Printf("请输入需要修改的年龄（原：%d）：", updateStu.Age)
			fmt.Scanln(&age)
			if age != 0 {
				updateStu.Age = age
			}

			fmt.Printf("请输入需要修改的邮箱（原：%s）：", updateStu.Email)
			fmt.Scanln(&email)
			if email != "" {
				updateStu.Email = email
			}
			fmt.Println("修改成功！")
			break
		} else {
			fmt.Println("学生不存在，请重新输入。")
		}
	}
}

func (ss *StudentService) DeleteStu() {
	fmt.Printf("请输入需要删除的学生编号：")
	var inputNum int
	fmt.Scan(&inputNum)
	deleteNum := ss.stuIsExist(inputNum)
	if deleteNum != -1 {
		ss.Student = append(ss.Student[:deleteNum], ss.Student[deleteNum+1:]...)
	} else {
		fmt.Println("用户不存在！")
	}
}

func (ss *StudentService) SaveData() {
	data, _ := json.Marshal(ss)
	ioutil.WriteFile("db/data.json", data, 0666)
}
